﻿using Autofac.Integration.Mvc;
using CNKI.TPI.Web.Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace CNKI.TPI.Web.UI
{
    /// <summary>
    /// picture 的摘要说明
    /// </summary>
    public class picture : IHttpHandler
    {
        System.Drawing.Image GetImageFromServer(string key, string e)
        {
            //byte[] d = new byte[1024];
            //debug
            IDataContext dataContext = AutofacDependencyResolver.Current.GetService<IDataContext>();
            byte[] d = dataContext.GetBinary(key);
            if (d == null)
            {
                return null;
            }
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream(d))
            {
                System.Drawing.Image obj = System.Drawing.Image.FromStream(ms, false, true);
                ms.Flush();
                return obj;
            }

        }

        private static bool IsTrue()
        {
            return true;
        }

        System.Drawing.Image Convert(System.Drawing.Image img, string width)
        {
            int x;
            int y;

            if (string.IsNullOrEmpty(width))
            {
                x = img.Width;
                y = img.Height;
            }
            else
            {
                x = int.Parse(width);
                float c = (float)img.Width / (float)img.Height;
                y = (int)((float)x / c);
            }
            try
            {
              
                if (x == 0 || y == 0)
                {
                    return img;
                }
                System.Drawing.Image.GetThumbnailImageAbort call = new System.Drawing.Image.GetThumbnailImageAbort(IsTrue);
                System.Drawing.Image newimg = img.GetThumbnailImage(x, y, call, IntPtr.Zero);

                img.Dispose();
                return newimg;

            }
            catch (Exception ex)
            {
                LogOpr.Error(ex.ToString());
                return img;
            }

        }

        public static byte[] ImageToBytes(System.Drawing.Image img, System.Drawing.Imaging.ImageFormat imageFormat)
        {
            if (img == null)
            {
                return null;
            }
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {
                using (System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(img))
                {
                    bmp.Save(ms, imageFormat);
                    ms.Position = 0;
                    byte[] data = new byte[ms.Length];
                    ms.Read(data, 0, (int)ms.Length);
                    ms.Flush();
                    return data;
                }
            }
        }

        private static System.Collections.Hashtable memCache = new System.Collections.Hashtable();
        private static Queue<string> memQueue = new Queue<string>();

        byte[] GetImageFromCache(string name, string size)
        {
            string key = string.Format("{0}_{1}", name, size);
            key = key.ToLower();

            lock (memCache)
            {
                if (memCache.ContainsKey(key))
                {
                    return (byte[])memCache[key];
                }
            }

            return null;
        }

        void AddImageCache(string name, string size, byte[] img)
        {
            if (string.IsNullOrEmpty(size))
            {
                size = "";
            }

            string key = string.Format("{0}_{1}", name, size);
            key = key.ToLower();

            lock (memCache)
            {
                int maxsize = 1024;
                if (string.IsNullOrEmpty(System.Configuration.ConfigurationManager.AppSettings["piccache"]))
                {
                    maxsize = int.Parse(System.Configuration.ConfigurationManager.AppSettings["piccache"]);
                }
                
                if (memCache.Count > maxsize)
                {
                    RemoveImageCache();
                }

                if (!memCache.ContainsKey(key))
                {
                    memCache.Add(key, img);
                    memQueue.Enqueue(key);
                }
            }
        }

        void RemoveImageCache()
        {
            if (memQueue.Count != 0)
            {
                string key = memQueue.Dequeue();
                memCache.Remove(key);
            }
        }

        public void ProcessRequest(HttpContext context)
        {
            string key = context.Request.QueryString["picname"];
           
            string width = context.Request.QueryString["w"];
            
            byte[] data = GetImageFromCache(key, width);
            if (data != null)
            {
                context.Response.BinaryWrite(data);
                context.Response.End();
                return;
            }
            
            System.Drawing.Image img = GetImageFromServer(key, ".jpg");
            if (img == null)
            {
                return;
            }

            System.Drawing.Image obj = Convert(img, width);
            if (obj == null)
            {
                return;
            }

            data = ImageToBytes(obj, System.Drawing.Imaging.ImageFormat.Jpeg);
            AddImageCache(key, width, data);

            context.Response.BinaryWrite(data);
            context.Response.End();
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}